package com.pig4cloud.pig.ads.runner;

import com.pig4cloud.pig.ads.gdt.service.IGdtAdService;
import com.pig4cloud.pig.api.gdt.dto.GdtAdDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SynGdtAdvAdidWorker implements Runnable {

	private IGdtAdService iGdtAdService;

	private String accountId;

	private List<Long> advAdidIds;

	//最大重试次数
	private static final Integer tryTimes = 6;
	//重试间隔时间单位秒
	private static final Integer[] intervalTime = {15, 60, 120, 150, 300, 600};

	public SynGdtAdvAdidWorker(IGdtAdService iGdtAdService, String accountId, List<Long> advAdidIds) {
		this.iGdtAdService = iGdtAdService;
		this.accountId = accountId;
		this.advAdidIds = advAdidIds;
	}


	@Override
	public void run() {
		try {
			if(CollectionUtils.isNotEmpty(advAdidIds)){
				Integer retryNum = 1;
				while (retryNum <= tryTimes) {
					try {
						String ids = StringUtils.join(advAdidIds.toArray(), ",");
						GdtAdDto gdtAdDto = new GdtAdDto();
						gdtAdDto.setAccountId(accountId);
						gdtAdDto.setAdIds(ids);
						iGdtAdService.getGdtAdData(gdtAdDto);

						TimeUnit.SECONDS.sleep(intervalTime[retryNum-1]);
						retryNum++;
					} catch (Throwable e) {
						retryNum++;
						TimeUnit.SECONDS.sleep(intervalTime[retryNum - 1]);
						continue;
					}
				}
			}
		}catch(Throwable e){
			log.error("拉取广点通广告失败", e);
		}
	}
}
